package com.mike.service.impl;

import com.mike.mapper.TokenMapper;
import com.mike.mapper.UserMapper;
import com.mike.po.Token;
import com.mike.po.User;
import com.mike.service.CodeServiceFeignClient;
import com.mike.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * @Description
 * @Date 2021/11/29 11:07
 * @Created by mike
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TokenMapper tokenMapper;

    @Autowired
    private CodeServiceFeignClient codeClient;

    /**
     * 注册接⼝，true成功，false失败
     *
     * @return true/false
     */
    @Override
    @Transactional
    public Integer register(HttpServletResponse response, String email, String password, String code) {
        Integer validate = codeClient.validateCode(email, code);
        if (validate == 0) {
            User user = new User();
            user.setEmail(email);
            user.setPassword(password);
            user.setCreateTime(new Timestamp(System.currentTimeMillis()));
            userMapper.save(user);
            String token = generateToken();
            Token saveToken = new Token();
            saveToken.setToken(token);
            saveToken.setEmail(email);
            tokenMapper.save(saveToken);
            addCookie(response,token);
            return validate;
        }
        return validate;
    }

    /**
     * 是否已注册，根据邮箱判断,true代表已经注册过，
     * false代表尚未注册
     *
     * @return true/false
     */
    @Override
    public Boolean isRegistered(String email) {
        User user = new User();
        user.setEmail(email);
        return userMapper.findOne(Example.of(user)).isPresent();
    }

    /**
     * 登录接⼝，验证⽤户名密码合法性，根据⽤户名和
     * 密码⽣成token，此处使用uuid模拟,token存⼊数据库，并写⼊cookie
     * 中，登录成功返回邮箱地址，重定向到欢迎⻚
     *
     * @return 邮箱地址
     */
    @Override
    @Transactional
    public String login(HttpServletResponse response, String email, String password) {
        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        Optional<User> userOptional = userMapper.findOne(Example.of(user));
        if (userOptional.isEmpty()){
            return "false";
        }
        String token = generateToken();
        Token saveToken = new Token();
        saveToken.setToken(token);
        saveToken.setEmail(email);
        tokenMapper.save(saveToken);
        addCookie(response, token);
        return userOptional.get().getEmail();
    }

    // 将token写⼊cookie中
    private void addCookie(HttpServletResponse response, String token) {
        Cookie cookie = new Cookie("token", token);
        // 设置token超时时间5分钟
        cookie.setMaxAge(5 * 60);
        // 设置token作用域
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    // 生成token,此处使用uuid模拟
    private String generateToken() {
        return UUID.randomUUID().toString();
    }

    /**
     * 根据token查询⽤户登录邮箱地址接⼝
     *
     * @return 邮箱地址
     */
    @Override
    public String getEmailByToken(String token) {
        Token queryToken = new Token();
        queryToken.setToken(token);

        Optional<Token> tokenOptional = tokenMapper.findOne(Example.of(queryToken));
        return tokenOptional.isEmpty() ? null : tokenOptional.get().getEmail();
    }

    @Override
    public List<User> list() {
        return userMapper.findAll();
    }
}
